const http = require('http');
const WebSocket = require('ws');
const wsConfig = require("../config/wsConfig");

/**
 * app 为express实例
 */
const webSocketServer = (app) => {
	const server = http.createServer(app);
	const ws = new WebSocket.Server({ port: wsConfig.port });;
	ws.on('connection', (socket) => {
	  console.log(`有一个新的连接: ${new Date().toDateString()}`);
	  socket.on('message', (data) => {
	    console.log(`收到客户端发来的信息: ${data}`);
	    socket.send(data);
	  });
		
	  socket.on('disconnect', () => {
	    console.log('客户端断开连接');
	  });
		
		if (wsConfig.cyclicSend) {
			setInterval(() => {
				socket.send(wsConfig.intervalData())
			}, wsConfig.intervalTime);
		}
	});
};

module.exports = { webSocketServer };

